﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MovieRental.Entities;
using MovieRental.SqlRepositoryLibrary.Converters;
using MovieRental.DataInterfaces;
using System.Data.SqlClient;
using MovieRental.GeneralDataExceptions;

namespace MovieRental.SqlRepositoryLibrary
{
    public class SqlEditionRepository : SqlRepository<EditionInfo, Guid, EditionConverter>, IEditionRepository
    {
        public SqlEditionRepository(string connectionString)
            : base(connectionString)
        {
        }

        protected override bool Contains(EditionInfo entity)
        {
            return Contains(entity.Id);
        }

        public override void Delete(EditionInfo entity)
        {
            Delete(entity.Id);
        }

        public IEnumerable<EditionInfo> LoadAllForMovie(Guid movieId)
        {
            using (var connection = ProvideConnection())
            {
                SqlCommand command = new SqlCommand();
                var mapping = (Converter as EditionConverter).Mapping;
                command.CommandText = string.Format("SELECT * FROM {0} WHERE {1}={2}", mapping.TableName, mapping["MovieId"].Name, "@MovieId");
                command.Parameters.Add("@MovieId", System.Data.SqlDbType.UniqueIdentifier);
                command.Parameters["@MovieId"].Value = movieId;
                command.Connection = connection;
                try
                {
                    return GetEnumerableFromReaderCommand(command);
                }
                catch (Exception ex)
                {
                    throw new DbConnectionException("Can't connect to the db.", ex);
                }
            }
        }
    }
}
